package cn.com.fattiger.framework.cms.admin.common.service.impl;

import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import cn.com.fattiger.framework.cms.admin.common.dao.QuestionRepository;
import cn.com.fattiger.framework.cms.admin.common.model.Question;
import cn.com.fattiger.framework.cms.admin.common.service.QuestionService;

@Service
public class QuestionServiceImpl implements QuestionService {

	@Autowired
	private QuestionRepository questionRepository;
	
	@Override
	public void save(Question entity) {
		questionRepository.save(entity);
	}

	@Override
	public void delete(Long id) {
		questionRepository.delete(id);
	}

	@Override
	public Page<Question> list(Integer page, Integer pageSize) {
		Pageable pageable = new PageRequest(page, pageSize);
		return questionRepository.findAll(pageable);
	}

	@Override
	public Question get(Long id) {
		return questionRepository.findOne(id);
	}

	@Override
	public Page<Question> list(Integer page, Integer pageSize,
			final Map<String, String> condition) {
		Pageable pageable = new PageRequest(page, pageSize, Direction.ASC, "sequence");
		Specification<Question> spec = new Specification<Question>(){
			@Override
			public Predicate toPredicate(Root<Question> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
				Path<String> idPath = root.get("questionnaireId");
				Integer id = Integer.parseInt(condition.get("questionnaireId"));
				cq.where(cb.equal(idPath, id));
				return null;
			}
		};
		return questionRepository.findAll(spec, pageable);
	}

	@Override
	public void update(Question question) {
		questionRepository.update(question.getContent(), question.getSequence(), question.getType(), question.getId());
	}

	@Override
	public List<Question> list(final Map<String, String> condition) {
		Specification<Question> spec = new Specification<Question>(){
			@Override
			public Predicate toPredicate(Root<Question> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
				Path<String> idPath = root.get("questionnaireId");
				Integer id = Integer.parseInt(condition.get("questionnaireId"));
				cq.where(cb.equal(idPath, id));
				return null;
			}
		};
		return questionRepository.findAll(spec);
	}

}
